﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;
using MvcContrib.Castle;
using RouteDebug;
using ScrumBox.Library.InversionOfControl;
using ScrumBox.Web.Components;
using ScrumBox.Web.Helpers;

namespace ScrumBox.Web
{
    public class GlobalApplication : HttpApplication, IContainerAccessor
    {
        private static readonly object _lockDummy = new object();
        private IWindsorContainer _container;
        private bool _initiliazed;

        #region IContainerAccessor Members

        public IWindsorContainer Container
        {
            get
            {
                if (!_initiliazed)
                {
                    lock (_lockDummy)
                    {
                        if (!_initiliazed)
                            InitializeWindsor();
                    }
                }

                return _container;
            }
        }

        #endregion

        protected void Application_Start()
        {
            InitializeWindsor();

            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));
            ControllerBuilder.Current.DefaultNamespaces.Add("ScrumBox.Web.Controllers");

            RouteConfigurator.RegisterRoutes(RouteTable.Routes);
            //RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
        }

        private void InitializeWindsor()
        {
            _container = new ScrumBoxContainer();
            IoC.Initialize(new WindsorDependencyResolver(_container));
            _initiliazed = true;
        }
    }
}